import axios from 'axios'
import { MessagePlugin } from 'tdesign-vue-next'
import { mockRequest } from '../mock'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'

// 判断是否启用模拟数据
const useMock = true // 开发环境下启用模拟数据

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 0) {
      return res.data
    }

    MessagePlugin.error(res.message || '服务器响应错误')
    
    if (res.code === 2000 || res.code === 2001) {
      setTimeout(() => {
        window.location.href = '/login'
      }, 1500)
    }
    
    return Promise.reject(new Error(res.message || '服务器响应错误'))
  },
  error => {
    let message = '网络请求失败'
    
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message = '未授权，请重新登录'
          setTimeout(() => {
            window.location.href = '/login'
          }, 1500)
          break
        case 403:
          message = '您没有权限访问该资源'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = error.response.data?.message || '请求失败'
      }
    } else if (error.request) {
      message = '服务器未响应'
    } else {
      message = error.message
    }

    MessagePlugin.error(message)
    return Promise.reject(error)
  }
)

// 保存原始的request方法
type RequestMethod = AxiosInstance['request']
const originalRequest: RequestMethod = request.request

// 重写请求方法，添加模拟数据支持
request.request = function(this: AxiosInstance, config: AxiosRequestConfig) {
  if (useMock) {
    // 使用模拟数据
    return mockRequest(config.url || '', config.method || 'get', config.data, config.params)
  }
  return originalRequest.call(this, config)
} as RequestMethod

// 使用模拟数据
if (useMock) {
  console.log('使用模拟数据，登录账号: admin, 密码: 123456')
}

export default request 